#!/bin/sh
#
# $FreeBSD$
#

# PROVIDE: ix-post-samba
# REQUIRE: samba_server

. /etc/rc.freenas

save_sambaSID()
{
	local sambaSID

	RO_FREENAS_CONFIG=$(ro_sqlite ${name} 2> /tmp/${name}.fail && rm /tmp/${name}.fail)
	trap 'rm -f ${RO_FREENAS_CONFIG}' EXIT

	sambaSID="$(${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} "
	SELECT
		cifs_SID
	FROM
		services_cifs
	ORDER BY
		-id
	LIMIT 
		1
	")"

	if [ -z "${sambaSID}" ]
	then
		export LOGNAME=anonymous
		sambaSID="$(/usr/local/bin/net getlocalsid | \
			cut -f2 -d: | awk '{ print $1 }')"

		${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} "
		UPDATE
			services_cifs
		SET
			cifs_SID = '${sambaSID}'
		"
	fi
}

samba_post_init()
{
	save_sambaSID
}

name="ix-post-samba"
start_cmd='samba_post_init'
stop_cmd=':'

load_rc_config $name
run_rc_command "$1"
